//
// Created by v on 24-5-15.
//

#include "control_service.h"
#include "mongoose.h"
#include "esp_log.h"

#define TAG "controlService"

typedef struct
{
    struct mg_mgr  mgr;
    char url[64];
    struct mg_connection *conn;
    bool can_send;
    bool exit;
} JKControlServiceHandle;

static JKControlServiceHandle controlServiceHandle;

static void ws_message_handler(struct mg_connection *conn, int ev, void *ev_data)
{
    if (ev == MG_EV_OPEN)
    {
        ESP_LOGI(TAG, "ev connection opened conn=[%p]\n", conn);
        controlServiceHandle.conn = conn;
//        conn->is_hexdumping = 1;
    }
    else if (ev == MG_EV_WS_OPEN)
    {
        ESP_LOGI(TAG, "Websocket connection opened conn=[%p]\n", conn);
        controlServiceHandle.can_send = true;
    }
    else if (ev == MG_EV_HTTP_MSG)
    {
        struct mg_http_message *hm = (struct mg_http_message *)ev_data;
        ESP_LOGI(TAG, "uri ");
        if (mg_match(hm->uri, mg_str("/control"), NULL)) {
            // Upgrade to websocket. From now on, a connection is a full-duplex
            // Websocket connection, which will receive MG_EV_WS_MSG events.
            mg_ws_upgrade(conn, hm, NULL);
//            ws_connection = c;
        }
        else
        {
            // Serve static files
            printf("Unmanaged request receive\n");
        }
    }
    else if (ev == MG_EV_WS_MSG)
    {
        // Got websocket frame. Received data is wm->data. save it into the Pipe streaming channel
        struct mg_ws_message *wm = (struct mg_ws_message *)ev_data;
        ESP_LOGI(TAG, "ws data [%s]", wm->data.buf);
        char end = 0;
    }
    else if (ev == MG_EV_CLOSE)
    {
        controlServiceHandle.can_send = false;
        ESP_LOGE(TAG, "Websocket is disconnected");
    }
}

int control_service_start(int port)
{
    mg_mgr_init(&controlServiceHandle.mgr);
    mg_log_set(MG_LL_DEBUG);
    snprintf(controlServiceHandle.url, sizeof(controlServiceHandle.url), "ws://0.0.0.0:%d/control", port);
    controlServiceHandle.conn = mg_http_listen(&controlServiceHandle.mgr, controlServiceHandle.url, ws_message_handler, &controlServiceHandle);
    if (!controlServiceHandle.conn)
    {
        ESP_LOGE(TAG, "ws connect failed");
    }
    ESP_LOGI(TAG, "control service start done [%p][%s]", controlServiceHandle.conn, controlServiceHandle.url);
    return 0;
}

int control_service_send_data(char *data, int len)
{
    if (controlServiceHandle.conn && controlServiceHandle.can_send)
    {
        return mg_ws_send(controlServiceHandle.conn, data, len, WEBSOCKET_OP_TEXT);
    }
    return -2;
}

int control_service_stop()
{
    mg_mgr_free(&controlServiceHandle.mgr);
    return 0;
}

int control_service_do_cycle()
{
    if (controlServiceHandle.conn)
    {
        mg_mgr_poll(&controlServiceHandle.mgr, 100);
    }
    return 0;
}
